<template>
  <div class="implementation-projects-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span>实施项目管理</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增项目
          </el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="项目名称">
            <el-input 
              v-model="searchForm.name" 
              placeholder="请输入项目名称"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="客户名称">
            <el-input 
              v-model="searchForm.customer" 
              placeholder="请输入客户名称"
              clearable
              style="width: 180px"
            />
          </el-form-item>
          <el-form-item label="项目状态">
            <el-select 
              v-model="searchForm.status" 
              placeholder="请选择状态"
              clearable
              style="width: 130px"
            >
              <el-option label="全部" value="" />
              <el-option label="待启动" value="pending" />
              <el-option label="进行中" value="inprogress" />
              <el-option label="已完成" value="completed" />
              <el-option label="已暂停" value="paused" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格区域 -->
      <el-table 
        :data="tableData" 
        border 
        stripe
        v-loading="loading"
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="name" label="项目名称" min-width="200" show-overflow-tooltip />
        <el-table-column prop="customer" label="客户名称" width="150" />
        <el-table-column prop="pm" label="项目经理" width="100" />
        <el-table-column prop="teamSize" label="团队人数" width="100" align="center">
          <template #default="{ row }">
            <el-tag>{{ row.teamSize }}人</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="progress" label="项目进度" width="150">
          <template #default="{ row }">
            <el-progress :percentage="row.progress" :status="getProgressStatus(row.progress)" />
          </template>
        </el-table-column>
        <el-table-column prop="status" label="项目状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startDate" label="开始日期" width="120" />
        <el-table-column prop="endDate" label="结束日期" width="120" />
        <el-table-column prop="budget" label="项目预算" width="120" align="right">
          <template #default="{ row }">
            ¥{{ row.budget.toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" align="center" fixed="right">
          <template #default="{ row }">
            <el-button 
              type="primary" 
              size="small" 
              link
              @click="handleView(row)"
            >
              <el-icon><View /></el-icon>
              查看
            </el-button>
            <el-button 
              type="primary" 
              size="small" 
              link
              @click="handleEdit(row)"
            >
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button 
              type="success" 
              size="small" 
              link
              @click="handleManageTeam(row)"
            >
              <el-icon><User /></el-icon>
              团队
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              link
              @click="handleDelete(row)"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="900px"
      :close-on-click-modal="false"
    >
      <el-form 
        ref="formRef" 
        :model="form" 
        :rules="rules" 
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入项目名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户名称" prop="customer">
              <el-input v-model="form.customer" placeholder="请输入客户名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目经理" prop="pm">
              <el-select v-model="form.pm" placeholder="请选择项目经理" style="width: 100%">
                <el-option label="张伟" value="张伟" />
                <el-option label="李娜" value="李娜" />
                <el-option label="王强" value="王强" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="待启动" value="pending" />
                <el-option label="进行中" value="inprogress" />
                <el-option label="已完成" value="completed" />
                <el-option label="已暂停" value="paused" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始日期" prop="startDate">
              <el-date-picker
                v-model="form.startDate"
                type="date"
                placeholder="选择开始日期"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束日期" prop="endDate">
              <el-date-picker
                v-model="form.endDate"
                type="date"
                placeholder="选择结束日期"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目预算" prop="budget">
              <el-input-number 
                v-model="form.budget" 
                :min="0"
                :step="10000"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目进度">
              <el-slider v-model="form.progress" :show-tooltip="true" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="实施范围">
          <el-checkbox-group v-model="form.scope">
            <el-checkbox value="config">系统配置</el-checkbox>
            <el-checkbox value="migration">数据迁移</el-checkbox>
            <el-checkbox value="training">用户培训</el-checkbox>
            <el-checkbox value="develop">二次开发</el-checkbox>
            <el-checkbox value="integration">系统集成</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="项目描述">
          <el-input 
            v-model="form.description" 
            type="textarea"
            :rows="4"
            placeholder="请输入项目描述"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="备注">
          <el-input 
            v-model="form.remark" 
            type="textarea"
            :rows="2"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 团队管理对话框 -->
    <el-dialog
      v-model="teamDialogVisible"
      title="团队管理"
      width="700px"
    >
      <div v-if="selectedProject">
        <el-alert 
          :title="`项目：${selectedProject.name}`" 
          type="info" 
          :closable="false"
          style="margin-bottom: 20px"
        />
        
        <el-button type="primary" size="small" @click="handleAddMember" style="margin-bottom: 15px">
          <el-icon><Plus /></el-icon>
          添加成员
        </el-button>

        <el-table :data="teamMembers" border>
          <el-table-column prop="name" label="姓名" width="100" />
          <el-table-column prop="role" label="角色" width="120">
            <template #default="{ row }">
              <el-tag>{{ row.role }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="responsibility" label="职责" />
          <el-table-column label="操作" width="100" align="center">
            <template #default="{ row }">
              <el-button 
                type="danger" 
                size="small" 
                link
                @click="handleRemoveMember(row)"
              >
                移除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, Search, Refresh, Edit, Delete, View, User
} from '@element-plus/icons-vue'

// 搜索表单
const searchForm = reactive({
  name: '',
  customer: '',
  status: ''
})

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('新增项目')
const formRef = ref()
const submitLoading = ref(false)

// 团队管理对话框
const teamDialogVisible = ref(false)
const selectedProject = ref(null)
const teamMembers = ref([])

// 表单数据
const form = reactive({
  id: null,
  name: '',
  customer: '',
  pm: '',
  status: 'pending',
  startDate: '',
  endDate: '',
  budget: 0,
  progress: 0,
  scope: [],
  description: '',
  remark: ''
})

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
  customer: [{ required: true, message: '请输入客户名称', trigger: 'blur' }],
  pm: [{ required: true, message: '请选择项目经理', trigger: 'change' }],
  startDate: [{ required: true, message: '请选择开始日期', trigger: 'change' }],
  endDate: [{ required: true, message: '请选择结束日期', trigger: 'change' }]
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    pending: 'info',
    inprogress: 'primary',
    completed: 'success',
    paused: 'warning'
  }
  return typeMap[status] || ''
}

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    pending: '待启动',
    inprogress: '进行中',
    completed: '已完成',
    paused: '已暂停'
  }
  return textMap[status] || status
}

// 获取进度状态
const getProgressStatus = (progress) => {
  if (progress === 100) return 'success'
  if (progress >= 80) return ''
  if (progress >= 50) return 'warning'
  return 'exception'
}

// 查询
const handleSearch = () => {
  pagination.page = 1
  loadData()
}

// 重置
const handleReset = () => {
  searchForm.name = ''
  searchForm.customer = ''
  searchForm.status = ''
  handleSearch()
}

// 重置表单
const resetForm = () => {
  form.id = null
  form.name = ''
  form.customer = ''
  form.pm = ''
  form.status = 'pending'
  form.startDate = ''
  form.endDate = ''
  form.budget = 0
  form.progress = 0
  form.scope = []
  form.description = ''
  form.remark = ''
  formRef.value?.clearValidate()
}

// 新增
const handleAdd = () => {
  resetForm()
  dialogTitle.value = '新增项目'
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑项目'
  Object.assign(form, { ...row })
  dialogVisible.value = true
}

// 查看
const handleView = (row) => {
  ElMessage.info('查看项目详情：' + row.name)
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除项目"${row.name}"吗？`, '提示', {
    type: 'warning'
  }).then(() => {
    const index = allData.findIndex(item => item.id === row.id)
    if (index > -1) {
      allData.splice(index, 1)
    }
    ElMessage.success('删除成功')
    loadData()
  }).catch(() => {})
}

// 团队管理
const handleManageTeam = (row) => {
  selectedProject.value = row
  teamMembers.value = [
    { id: 1, name: '张伟', role: '项目经理', responsibility: '项目整体管理' },
    { id: 2, name: '李娜', role: '实施顾问', responsibility: '系统配置与培训' },
    { id: 3, name: '王强', role: '技术顾问', responsibility: '技术支持与开发' }
  ]
  teamDialogVisible.value = true
}

// 添加成员
const handleAddMember = () => {
  ElMessage.info('添加团队成员')
}

// 移除成员
const handleRemoveMember = (row) => {
  ElMessageBox.confirm(`确定要移除"${row.name}"吗？`, '提示', {
    type: 'warning'
  }).then(() => {
    ElMessage.success('移除成功')
  }).catch(() => {})
}

// 提交
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate((valid) => {
    if (valid) {
      submitLoading.value = true
      setTimeout(() => {
        if (form.id) {
          // 编辑
          const index = allData.findIndex(item => item.id === form.id)
          if (index > -1) {
            allData[index] = { ...form, teamSize: allData[index].teamSize }
          }
          ElMessage.success('更新成功')
        } else {
          // 新增
          const newId = Math.max(...allData.map(item => item.id), 0) + 1
          allData.push({
            ...form,
            id: newId,
            teamSize: Math.floor(Math.random() * 8) + 3
          })
          ElMessage.success('新增成功')
        }
        dialogVisible.value = false
        submitLoading.value = false
        loadData()
      }, 1000)
    }
  })
}

// 分页改变
const handleSizeChange = (size) => {
  pagination.size = size
  loadData()
}

const handleCurrentChange = (page) => {
  pagination.page = page
  loadData()
}

// 生成模拟数据
const generateMockData = () => {
  const customers = ['XX集团', 'YY公司', 'ZZ制造', 'AA科技', 'BB商贸', '长城企业', '华润集团', '万科地产', '中石化', '联想科技']
  const pms = ['张伟', '李娜', '王强', '赵敏', '刘芳', '陈明']
  const statuses = ['pending', 'inprogress', 'completed', 'paused']
  const statusWeights = [0.1, 0.5, 0.3, 0.1] // 各状态的权重
  const projectTypes = ['ERP实施项目', '财务系统上线', 'CRM系统部署', 'OA办公系统', 'WMS仓库管理', 'MES制造执行', 'BI数据分析', '电商平台搭建']
  
  const data = []
  for (let i = 1; i <= 35; i++) {
    const customer = customers[Math.floor(Math.random() * customers.length)]
    const projectType = projectTypes[Math.floor(Math.random() * projectTypes.length)]
    
    // 根据权重选择状态
    const rand = Math.random()
    let status = 'inprogress'
    let cumWeight = 0
    for (let j = 0; j < statuses.length; j++) {
      cumWeight += statusWeights[j]
      if (rand <= cumWeight) {
        status = statuses[j]
        break
      }
    }
    
    const progress = status === 'completed' ? 100 : 
                    status === 'paused' ? Math.floor(Math.random() * 60) :
                    status === 'pending' ? 0 :
                    Math.floor(Math.random() * 90) + 10
    
    data.push({
      id: i,
      name: `${customer}${projectType}`,
      customer: customer,
      pm: pms[Math.floor(Math.random() * pms.length)],
      teamSize: Math.floor(Math.random() * 8) + 3,
      progress: progress,
      status: status,
      startDate: `2024-${String(Math.floor(Math.random() * 12) + 1).padStart(2, '0')}-${String(Math.floor(Math.random() * 28) + 1).padStart(2, '0')}`,
      endDate: `202${Math.random() > 0.5 ? '4' : '5'}-${String(Math.floor(Math.random() * 12) + 1).padStart(2, '0')}-${String(Math.floor(Math.random() * 28) + 1).padStart(2, '0')}`,
      budget: Math.floor(Math.random() * 900000) + 100000,
      scope: ['config', 'migration', 'training', 'develop', 'integration'].slice(0, Math.floor(Math.random() * 4) + 1)
    })
  }
  return data
}

// 存储所有数据
let allData = []

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 初始化数据（仅第一次）
    if (allData.length === 0) {
      allData = generateMockData()
    }
    
    // 筛选数据
    let filteredData = allData.filter(item => {
      if (searchForm.name && !item.name.includes(searchForm.name)) {
        return false
      }
      if (searchForm.customer && !item.customer.includes(searchForm.customer)) {
        return false
      }
      if (searchForm.status && item.status !== searchForm.status) {
        return false
      }
      return true
    })
    
    // 更新总数
    pagination.total = filteredData.length
    
    // 如果当前页没有数据，跳转到最后一页
    const maxPage = Math.ceil(pagination.total / pagination.size) || 1
    if (pagination.page > maxPage) {
      pagination.page = maxPage
    }
    
    // 分页切片
    const start = (pagination.page - 1) * pagination.size
    const end = start + pagination.size
    tableData.value = filteredData.slice(start, end)
    
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.implementation-projects-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-box {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>

